#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
阿土伯一期删除 v1部分
'''

import json
import sys
sys.path.append('/mnt/moonbrook/Moonbrook')
import subprocess
import os
import re
import psutil
import time
import requests
from copy import deepcopy
from datetime import datetime, timedelta
from pybloom_live import ScalableBloomFilter
from secret import batch_encrypt_decrypt_dict
from aes import contact_aes, name_aes
from apscheduler.schedulers.blocking import BlockingScheduler
from datastore.mongodb import MongoDBClientWrapper

from base import ExportAndTjBase
from utils import Utils
from models import MongoQueryConfig, RobotConfig
from robot import DingtalkRobot

reload(sys)
sys.setdefaultencoding('utf-8')


class ExportAndTj(ExportAndTjBase):
    def __init__(self, *args, **kwargs):
        super(ExportAndTj, self).__init__(*args, **kwargs)
        # todo other col
        # self.contact_col = self.db.p_col('contact')
        self.ent_col = self.db.p_col('enterprise')


    def handle_one_mongo_data(self, record_dic, save_result_dic=None):
        record_dic = Utils.decrypt_one_record(record_dic, need_decrypt=True, need_strf_time=True)
        contactChannelList = record_dic.get('contactChannelList')
        contact = record_dic.get('contact')
        contactType = record_dic.get('contactType')
        create_time = record_dic.get('create_time')
        import_update_time = record_dic.get('import_update_time')
        nameId = record_dic.get('nameId')
        name = record_dic.get('name')
        _id = record_dic.get('_id')
        if len(contactChannelList)!=1:
            return save_result_dic
        page_link = contactChannelList[0].get('contactPageLink')
        if not page_link:
            return save_result_dic

        if not name:
            dic = self.ent_col.find_one({'_id': nameId}, projection=['name'])
            if isinstance(dic, dict):
                ent_dic = Utils.decrypt_one_record(dic, need_strf_time=True, need_decrypt=True)
                name = ent_dic.get('name')

        is_api_flag =  True if page_link.count('ViewTel') else False
        dc_info = '{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n'.format(nameId, contact, contactType,page_link, create_time, import_update_time, name, _id,is_api_flag)
        self.write_dc_f.write(dc_info)


        return save_result_dic

    def run(self):

        save_result_dic = {
        }
        config = {
            MongoQueryConfig.col_name: 'contact',
            MongoQueryConfig.filter: {
                'contactType': {"$in": [0, 1, 2]},
                "contactChannelList.contactSource": re.compile(r'atobo$'),
                "create_time": {"$gte": datetime(year=2021,month=3,day=20)}
            },
            MongoQueryConfig.projection: ["contact","nameId","create_time","_id","contactChannelList","contactType","import_update_time","name"]
        }

        result_dic = self.get_data_from_mongo(config, save_result_dic)




def run(abs_file_name):
    export_and_tj = ExportAndTj(abs_file_name)
    export_and_tj.main()


def scheduler_run(abs_file_name):
    scheduler = BlockingScheduler()
    scheduler.add_job(func=run, trigger='cron',
                      args=(abs_file_name,),
                      # day_of_week="sun",
                      hour='20', minute='52', id='dd_run')
    scheduler.start()


if __name__ == '__main__':
    '''
    导出所有仅为v1来源的 且创建时间>=3月20日的 联系方式，
    需要针对创建时间6月12日 及接口进行单独统计
    '''
    file_name = '来源仅为v1的所有数据导出'
    # py文件名+file_name+小时时间
    abs_file_name = Utils.generate_abs_path(file_name,current_py_path=__file__)

    run(abs_file_name)
    # scheduler_run(abs_file_name)


